from nicegui import ui
import os

import requests


class RegisterView:
    def __init__(self):
        # 页面标题，全球影像采集系统
        ui.page_title("全球影像采集系统")

        # background img imgs/background.jpg
        ui.add_css("body {background-image: url('imgs/background.jpg');}")
        with ui.row().classes("w-full").style("margin-top: 5%;"):
            ui.markdown("# 全球影像采集系统").classes("w-full text-center text-white")
        with ui.card().classes("w-1/4 mx-auto").style("height: 50%;"):
            ui.label("注册").style("font-size: 20px;").classes("mx-auto")
            self.email = ui.input("邮箱").classes("w-full")
            self.passwd1 = ui.input(
                "密码", password=True, password_toggle_button=True
            ).classes("w-full")
            # 确认密码
            self.passwd2 = ui.input(
                "确认密码", password=True, password_toggle_button=True
            ).classes("w-full")

            with ui.row():
                ui.button("注册").on_click(lambda: self.register())
                # 返回登录
                ui.button("返回登录").on_click(lambda: ui.navigate.to("login"))

    def register(
        self,
    ):
        if self.passwd1.value != self.passwd2.value:
            ui.notify("两次密码不一致", type="negative")
            return
        register_url = os.getenv("BACKEND_URL") + os.getenv("REGISTER_URL")
        # request
        method = os.getenv("REGISTER_METHOD")
        data = {
            "email": self.email.value,
            "password": self.passwd1.value,
            "repeatPassword": self.passwd2.value,
        }
        response = requests.request(method, register_url, data=data)
        if response.status_code == 200:
            ui.notify("注册成功", type="positive")
            ui.navigate.to("login")
        else:
            ui.notify(f"注册失败\n{response.text}", type="negative")
            print(response.text)
